package com.leyou.order.service.interceptor;

import com.leyou.auth.inter.pojo.UserInfo;
import com.leyou.auth.inter.util.JwtUtils;
import com.leyou.auth.inter.util.TokenState;
import com.leyou.common.bean.Constant;
import com.leyou.common.bean.Result;
import com.leyou.common.bean.ResultCode;
import com.leyou.common.util.CookieUtils;
import com.leyou.common.util.JsonUtils;
import com.leyou.common.util.StringUtil;
import com.leyou.order.service.config.JwtProperties;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

@Slf4j
public class LoginInterceptor extends HandlerInterceptorAdapter {

    @Autowired
    private JwtProperties jwtProperties;

    @Autowired
    private StringRedisTemplate redisTemplate;

    // 定义一个线程域，存放登录用户
    private static final ThreadLocal<UserInfo> THREAD_LOCAL = new ThreadLocal<>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取请求头中的token
        String token = request.getHeader("x-authorize-token");
        if(!StringUtil.isEmpty(token)){
            log.info("非法访问，未登录");
            this.response(response,ResultCode.S_SYSTEM_VISIT_EXCEPTION);
            return false;
        }
        UserInfo userInfo = null;
        Map<String, Object> map = JwtUtils.validParseJWT(token, this.jwtProperties.getPublicKey());
        switch ((TokenState)map.get("state")){
            case VALID:
                userInfo = (UserInfo) map.get("userInfo");
                String key = Constant.KEY_TOKEN_ID+userInfo.getId();
                String cacheToken = this.redisTemplate.opsForValue().get(key);
                if(!StringUtil.isEmpty(cacheToken)){
                    log.info("token已过期");
                    this.response(response,ResultCode.V_TOKEN_EXP);
                    return false;
                }
                //防止一直持有过期Token访问
                if(!token.equals(cacheToken)){
                    log.info("token已过期");
                    this.response(response,ResultCode.V_TOKEN_EXP);
                    return false;
                }
                break;
            case EXPIRED:
                log.info("token已过期");
                this.response(response,ResultCode.V_TOKEN_EXP);
                return false;
            case SIGNATURE:
                log.info("token签名异常");
                this.response(response,ResultCode.V_TOKEN_UNAUTHORIZED_FAIL);
                return false;
            case ISS_EXCEPTION:
                log.info("token签发者异常");
                this.response(response,ResultCode.V_TOKEN_UNAUTHORIZED_FAIL);
                return false;
            case ANALYSIS_EXCEPTION:
                log.info("token解析异常");
                this.response(response,ResultCode.V_TOKEN_UNAUTHORIZED_FAIL);
                return false;
            default:
                break;
        }
        // 解析成功，放入线程域
        THREAD_LOCAL.set(userInfo);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        THREAD_LOCAL.remove();
    }

    public static UserInfo getLoginUser() {
        return THREAD_LOCAL.get();
    }

    public void response(HttpServletResponse response,ResultCode code)throws Exception{
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().write(JsonUtils.serialize(Result.newFailure(code)));
        response.getWriter().flush();
    }
}